﻿using System;
using System.Collections.Generic;

namespace CodeCounsel.SharePoint2010.DigiD
{
    /// <summary>
    /// Represents message contained in the HTTP request that a user makes after being 
    /// authenticated and redirected by DigiD.
    /// </summary>
    class AuthenticationMessage
    {
        #region [Fields]
        Dictionary<string, string> _parameters;
        #endregion

        #region [Properties]
        /// <summary>
        /// The ID of the request.
        /// </summary>
        public string RequestID { get { return _parameters[Schema.RequestID]; } }
        /// <summary>
        /// The authenticated user credentials.
        /// </summary>
        public string Credentials { get { return _parameters[Schema.ASelectCredentials]; } }
        /// <summary>
        /// The server address where the credentials can be verified.
        /// </summary>
        public string ServerID { get { return _parameters[Schema.ASelectServer]; } }
        #endregion

        #region [Constructors]
        /// <summary>
        /// Made private to force validation of the parameters.
        /// </summary>
        /// <param name="parameters">The parameters received in the HTTP request query string.</param>
        AuthenticationMessage(Dictionary<string, string> parameters)
        {
            _parameters = parameters;
        }
        #endregion

        #region [Public methods]
        /// <summary>
        /// Creates and validates a AuthenticationMessage based on the parameters 
        /// received in the query string of a Uri.
        /// </summary>
        /// <param name="uri">The Uri containing the parameters to parse.</param>
        /// <returns>A validated Authentication message.</returns>
        public static AuthenticationMessage CreateFromUri(Uri uri)
        {
            AuthenticationMessage message = new AuthenticationMessage(uri.GetQuery());
            ValidateMessage(message);
            return message;
        }
        #endregion

        #region [Private methods]
        static void ValidateMessage(AuthenticationMessage message)
        {
            if (String.IsNullOrEmpty(message.RequestID) ||
                String.IsNullOrEmpty(message.Credentials) ||
                String.IsNullOrEmpty(message.ServerID))
            {
                throw new DigiDException("The authentication message received from DigiD is incomplete.");
            }
        }
        #endregion
    }
}
